//
//  AddContactsViewController.m
//  Leo01
//
//  Created by 张旭 on 15/9/26.
//  Copyright (c) 2015年 张旭. All rights reserved.
//

#import "AddContactsViewController.h"
#import "ImportPageViewController.h"

#import "SyncManager.h"
#import "DataManager.h"
#import "LeoMsg.h"
#import "AppDelegate.h"

@interface AddContactsViewController ()


@property (nonatomic,retain) SyncManager *syncManager;
@property (nonatomic,retain) DataManager *dataManager;

//通讯录用参数
@property (nonatomic,retain) NSString *AdBookName;
@property (nonatomic,retain) NSString *AdBookPhone;

@property(nonatomic,strong) UIActionSheet *actionSheet;
@property(nonatomic,strong) UIImagePickerController *picker;
@property(nonatomic,strong) NSString *photoUrl;
@property(nonatomic,strong) NSString *photoName;

@end



@implementation AddContactsViewController
@synthesize nameTextField;
@synthesize phoneNumberTextField;
@synthesize importButton;
@synthesize navLeftButton;
@synthesize navRightButton;
@synthesize avatarImageView;
@synthesize avatarBaseView;

//通讯录用参数
@synthesize AdBookName;
@synthesize AdBookPhone;

//判断某个电话号码是否为管理员

-(BOOL)thePhoneIsManager:(NSString *)phone
{
    self.dataManager=[[DataManager alloc]init];
    
    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;
    
    NSArray *ManagersArray = [self.dataManager getManagerLists:watchId accountId:userId];
    for (int i=0;i<ManagersArray.count;i++)
    {
        Manager *manager=[ManagersArray objectAtIndex:i];
        if (manager.phone==phone){return YES;}
        if ([phone isEqualToString:manager.phone]){return YES;}
    }
    
    return NO;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [nameTextField resignFirstResponder];
    [phoneNumberTextField resignFirstResponder];
}
-(void)dealloc
{
    self.syncManager=NULL;
    AdBookName=NULL;
    AdBookPhone=NULL;
    self.actionSheet=NULL;
    self.picker=NULL;
    self.photoUrl=NULL;
    self.photoName=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title=@"添加联系人";
    self.navigationItem.rightBarButtonItem=navRightButton;
    
    [self initNavButton];
    [self initImportButton];
    [self beforeCamara];
    self.syncManager=[[SyncManager alloc] init];
    // Do any additional setup after loading the view from its nib.
}


- (void)initNavButton {
    [navLeftButton setTarget:self];
    [navLeftButton setAction:@selector(back)];
    
    [navRightButton setTarget:self];
    [navRightButton setAction:@selector(saveContact)];
    
    //头像切圆代码
    self.avatarImageView.layer.cornerRadius = self.avatarImageView.frame.size.width / 2;
    self.avatarImageView.clipsToBounds = YES;
    
    //进入相册手势添加
    UITapGestureRecognizer *tapReconizerToPic = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(setImg)];
    [self.avatarBaseView addGestureRecognizer:tapReconizerToPic];
    nameTextField.delegate=self;
    phoneNumberTextField.delegate=self;
}

- (void)initImportButton{
    [importButton addTarget:self action:@selector(importContacts) forControlEvents:UIControlEventTouchDown];
}

- (void)importContacts{
    //ImportPageViewController *importPageViewController = [[ImportPageViewController alloc]init];
    //[self.navigationController pushViewController:importPageViewController animated:YES];
    
    //新的通讯录导入代码
    [self initAdBook];
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
    //[self dismissViewControllerAnimated:YES completion:nil];
}

- (void)saveContact{
    
    if((nameTextField.text==NULL)||([nameTextField.text isEqualToString:@""]))
    {
        [LeoMsg showMsg:@"姓名不能为空，请检查后再保存"];
        return;
    }
    if ([LeoMsg isTooLong:nameTextField.text ChnLength:12 EngLength:10 tipsString:@"联系人名" onlyUnderline:YES])
    {
        return;
    }
    if((phoneNumberTextField.text==NULL)||([phoneNumberTextField.text isEqualToString:@""]))
    {
        [LeoMsg showMsg:@"电话号码不能为空"];
        return;
        
    }
    if ([self checkContactIfExist:phoneNumberTextField.text]){
        [LeoMsg showMsg:@"联系人已存在"];
        return;
    }

    
//    if (![self validateMobile:phoneNumberTextField.text])
//    {
//        [LeoMsg showMsg:@"输入的手机号码无效，请输入正确的手机号码"];
//        return;
//
//    }
    if ([LeoMsg ContactPhoneFormatIsWrong:phoneNumberTextField.text])
    {
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        [LeoMsg showMsg:@"程序发生错误，code is 2"];
        return;
    }
    DataManager *dataManager=[[DataManager alloc] init];
    Watch *watch=[dataManager getActiveWatch:user.uid];
    NSString *name=nameTextField.text;
    NSString *phone=phoneNumberTextField.text;
    Contact *contact1=[[Contact alloc] init];
    contact1.phoneNum=phone;
    contact1.contactname=name;
    contact1.type=0;
    contact1.groupId=13;
    contact1.deviceUid=watch.deviceUid;
    
    if (self.photoUrl==NULL)
    {

    }
    else
    {
        contact1.photoName=self.photoName;
        contact1.photo_url=self.photoUrl;
    }
    
    if ([self thePhoneIsManager:phone])
    {
        [LeoMsg showMsg:@"此号码已是管理员!"];
        return ;
    }
    if(dataManager==NULL)
        return;
    if([dataManager IsSameContact:watch.deviceUid contact:contact1 isNew:YES]==YES)
    {
        [LeoMsg showMsg:@"联系人已存在"];
        return;
    }
    self.syncManager=[[SyncManager alloc] init];
    [self.syncManager addWatchContact:contact1 completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        //[self callback:result retValue:retValue description:description];
        if(result==SUCESS)
        {
            [LeoMsg showMsg:@"添加成功!"];
            [self.navigationController popViewControllerAnimated:YES];
            
        }
        else
        {
            //[LeoMsg showMsg:@"添加失败!"];
            [Tooler showHttpMsg:result description:description msg:@"添加联系人失败"];
            //[self.navigationController popViewControllerAnimated:YES];
        }
    }];


    //submit and save
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
//-(void)callback:(SyncResult) result retValue:(NSDictionary *)ret description:(NSString *)description
//{
//    
//    if(result==SUCESS)
//    {
//        NSLog(@"sync result is sucess");
//    }
//    else
//    {
//        NSLog(@"sync fail,error is %@",description);
//        if(description!=NULL)
//        {
//            [LeoMsg showMsg:description];
//        }
//        else
//        {
//            [LeoMsg showMsg:@"添加联系人失败"];
//        }
//    }
//}


//***通讯录代码
//初始化通讯录
-(void)initAdBook
{
    ABPeoplePickerNavigationController *nav = [[ABPeoplePickerNavigationController alloc] init];

    nav.peoplePickerDelegate = self;
//    //去除导航栏下1像素黑线代码
//    UIColor *blueBackgroundColor=[UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:1];
//    UIImage *blueBackgroundImage=[self imageWithColor:blueBackgroundColor];
//    
////    UINavigationBar *navigationBar = nav.topViewController.navigationController.navigationBar;
////    // white.png图片自己下载个纯白色的色块，或者自己ps做一个
////    [navigationBar setBackgroundImage:blueBackgroundImage
////                       forBarPosition:UIBarPositionAny
////                           barMetrics:UIBarMetricsDefault];
////    [navigationBar setShadowImage:[UIImage new]];
//    //[[UINavigationBar appearanceWhenContainedIn:[ABPeoplePickerNavigationController class], nil] setBackgroundImage:blueBackgroundImage forBarMetrics:UIBarMetricsDefault];
//    [[UINavigationBar appearanceWhenContainedIn:[ABPeoplePickerNavigationController class], nil] setBarTintColor:[UIColor whiteColor]];
//    [[UINavigationBar appearanceWhenContainedIn:[ABPeoplePickerNavigationController class], nil] setBackgroundColor:[UIColor redColor]];
//    [self setNavProperty:nav];
//    

//
//    [nav.topViewController.navigationController.navigationBar setBackgroundColor:[UIColor colorWithRed:72/255.0 green:179/255.0 blue:247/255.0 alpha:1.0]];
//
//    //nav.navigationBar.backgroundColor=[UIColor colorWithRed:72/255.0 green:179/255.0 blue:24/255.0 alpha:1.0];
//    nav.topViewController.navigationController.navigationBar.tintColor=[UIColor whiteColor];
    
    
    //[[UINavigationBar appearanceWhenContainedIn:[ABPeoplePickerNavigationController class],  nil]setBackgroundColor:[UIColor colorWithRed:72/255.0 green:179/255.0 blue:24/255.0 alpha:1.0]];
    //[[UINavigationBar appearance] setBackgroundColor:[UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:1.0]];
    //[[UINavigationBar appearance]setTranslucent:NO];
    //[[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]}];

    
    [[UINavigationBar appearance] setTintColor:[UIColor blackColor]];
    
    
    double version = [[UIDevice currentDevice].systemVersion doubleValue];//判定系统版本。
    if(version>8.0f){
        nav.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];
    }
   // [self.navigationController pushViewController:nav animated:YES];
    [self presentViewController:nav animated:YES completion:nil];
}
//取消选择
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

}
//IOS8
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    
    
    
    NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
    NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
    NSString *middleName = (__bridge NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);
    
    if (firstName==NULL){firstName=@"";}
    if (lastName==NULL){lastName=@"";}
    if (middleName==NULL){middleName=@"";}
    
    NSString *fullName=[lastName stringByAppendingString:middleName];
    fullName=[fullName stringByAppendingString:firstName];
    
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
    NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
    
    if ([phoneNO hasPrefix:@"+"]) {
        phoneNO = [phoneNO substringFromIndex:3];
    }
    
    phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSLog(@"%@", fullName);
    NSLog(@"%@", phoneNO);
    
    AdBookPhone=phoneNO;
    AdBookName=fullName;
    nameTextField.text=fullName;
    phoneNumberTextField.text=phoneNO;
    
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

    return;
    
    
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person
{
    ABPersonViewController *personViewController = [[ABPersonViewController alloc] init];
    personViewController.displayedPerson = person;
    [peoplePicker pushViewController:personViewController animated:YES];
}
//IOS 7

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
    return YES;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
    NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
    NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
    NSString *middlename = (__bridge NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);
    
    NSString *fullName=[lastName stringByAppendingString:middlename];
    fullName=[fullName stringByAppendingString:firstName];
    
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
    NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
    
    if ([phoneNO hasPrefix:@"+"]) {
        phoneNO = [phoneNO substringFromIndex:3];
    }
    
    phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSLog(@"%@", fullName);
    NSLog(@"%@", phoneNO);
    
    AdBookPhone=phoneNO;
    AdBookName=fullName;
    
    nameTextField.text=fullName;
    phoneNumberTextField.text=phoneNO;
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

    
    
    return YES;
}
//通讯录代码结束



//相机相册部分
- (void)setImg{
    //NSLog(@"123");
    [self.actionSheet showInView:self.view];
    
}


-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self camera];
    }else if (buttonIndex == 1) {
        [self LocalPhoto];
    }else if(buttonIndex == 2) {
        
    }
    
}
-(void)beforeCamara
{
    self.actionSheet = [[UIActionSheet alloc]
                        initWithTitle:nil
                        delegate:self
                        cancelButtonTitle:nil
                        destructiveButtonTitle:nil
                        otherButtonTitles:@"拍照", @"从手机相册选择",@"取消",nil];
    self.actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    self.picker = [[UIImagePickerController alloc] init];
    self.picker.delegate = self;
    //设置选择后的图片可被编辑
    self.picker.allowsEditing = YES;
    
    self.picker.navigationBar.translucent =NO;
    
    [self.picker.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    [self.picker.navigationBar setBarTintColor:[UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:1.0]];
}

-(void)LocalPhoto
{
    self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    //[[UINavigationBar appearance] setTintColor:[UIColor blackColor]];
    [self presentViewController:self.picker animated:YES completion:nil];
}
-(void)camera
{
    self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    //[[UINavigationBar appearance] setTintColor:[UIColor blackColor]];
    [self presentViewController:self.picker animated:YES completion:nil];
}
//取消选择
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        NSData *data=UIImageJPEGRepresentation(image, 0.3);
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [[Tooler getDocumentDirectory] stringByAppendingString:@"/headimg"];
        if([Tooler isDirectoryExist:DocumentsPath])
        {
            NSString *ts=[Tooler getTS];
            self.photoName=[NSString stringWithFormat:@"/headimg/image%@.jpg",ts];
            //得到选择后沙盒中图片的完整路径
            self.photoUrl = [[NSString alloc]initWithFormat:@"%@/image%@.jpg",DocumentsPath,ts];
            NSError *error;
            [data writeToFile:self.photoUrl options:NSDataWritingFileProtectionComplete error:&error];
            if(error==NULL)
            {
                self.avatarImageView.image=[UIImage imageNamed:self.photoUrl];
            }
            
        }
        
        [self.picker dismissViewControllerAnimated:YES completion:nil];
        [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

        
    }
    
}
//***键盘遮挡部分
//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGFloat kbHeight =300;
    int INTERVAL_KEYBOARD=258;

    //t offset = frame.origin.y + 32 - (self.view.frame.size.height - 500);//键盘高度300
    CGFloat offset = (textField.frame.origin.y+textField.frame.size.height+INTERVAL_KEYBOARD) - (self.view.frame.size.height - kbHeight);

    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    NSLog(@"%d",offset);

    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    if(offset > 0)
        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
    
    [UIView commitAnimations];
}

//当用户按下return键或者按回车键，keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}


//校验手机号码
- (BOOL)validateMobile:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        //判断固定号码
        

//        NSString *parten =@"[0-9]{11}";
//        if ([self checkRegular:parten Target:mobileNum]&&(mobileNum.length==11)){return YES;}
//        parten =@"[0-9]{5}";
//        if ([self checkRegular:parten Target:mobileNum]&&(mobileNum.length==5)){return YES;}
//        parten =@"[0-9]{5}";
        return NO;
    }
}
-(BOOL)checkRegular:(NSString*)parten Target:(NSString*)staString
{
    //NSString *staString =mobileNum;
    
    //NSString *parten =@"[0-9]{11}";
    
    NSError* error = NULL;
    
    NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:parten options:nil error:&error];
    
    NSArray* match = [reg matchesInString:staString options:NSMatchingCompleted range:NSMakeRange(0, [staString length])];
    
    if (match.count != 0)
    {
        for (NSTextCheckingResult *matc in match)
        {
            NSRange range = [matc range];
            NSLog(@"%lu,%lu,%@",(unsigned long)range.location,(unsigned long)range.length,[staString substringWithRange:range]);
        }
        return YES;
    }
    return NO;
}
-(void)setNavProperty:(UINavigationController *)navigationController
{
    navigationController.navigationBar.translucent =NO;
    navigationController.extendedLayoutIncludesOpaqueBars = YES;
    
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
//    [[UINavigationBar appearance] setBackgroundColor:[UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:1.0]];

    [navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    [navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:1.0]];
    //去除导航栏下1像素黑线代码
    UIColor *blueBackgroundColor=[UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:1];
    UIImage *blueBackgroundImage=[self imageWithColor:blueBackgroundColor];
    
    UINavigationBar *navigationBar = navigationController.navigationBar;
    // white.png图片自己下载个纯白色的色块，或者自己ps做一个
    [navigationBar setBackgroundImage:blueBackgroundImage
                       forBarPosition:UIBarPositionAny
                           barMetrics:UIBarMetricsDefault];
    [navigationBar setShadowImage:[UIImage new]];
    //去除结束
    
}
- (UIImage *)imageWithColor:(UIColor *)color
{
    float width=[UIScreen mainScreen].bounds.size.width;
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

//判断是否存在联系人
-(BOOL)checkContactIfExist:(NSString*)phoneNum
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.ManagerDetailsDataArray = [[NSMutableArray alloc]init];
    myDelegate.ContactsDetailsDataArray = [[NSMutableArray alloc]init];
    myDelegate.SosContactsDetailsDataArray = [[NSMutableArray alloc]init];
    
    User *user=[User sharedSingleton];
    NSString *userId=user.uid;
    Watch *watch=[self.dataManager getActiveWatch:userId];
    NSString *watchId=watch.deviceUid;
    
    NSArray *ContactsArray = [self.dataManager getContactLists:watchId accountId:userId];
    NSArray *ManagersArray = [self.dataManager getManagerLists:watchId accountId:userId];
    NSArray *SosContactsArray = [self.dataManager getSOSContactLists:watchId accountId:userId];
    
    //增加watch到ContactArray中
    NSMutableArray *newContactsArray=[[NSMutableArray alloc]initWithArray:ContactsArray];
    NSArray *watchContacts=[self.dataManager getWatchContacts:watchId role:watch.role];
    if (watchContacts!=NULL){
        for (int j=0;j<watchContacts.count;j++){
            [newContactsArray addObject:[watchContacts objectAtIndex:j]];
        }
    }
    ContactsArray=newContactsArray;
    
    
    
    for (int i=0;i<ContactsArray.count;i++)
    {
        if ([[ContactsArray objectAtIndex:i] isKindOfClass:[Manager class]])
        {
            Manager *manager=[[Manager alloc]init]; manager=[ContactsArray objectAtIndex:i];
            if ([manager.phone isEqualToString:phoneNum]){return YES;}
        }
        if ([[ContactsArray objectAtIndex:i] isKindOfClass:[Contact class]]){
            Contact *contact=[[Contact alloc]init]; contact=[ContactsArray objectAtIndex:i];
            if ([contact.phoneNum isEqualToString:phoneNum]){return YES;}
        };
        if ([[ContactsArray objectAtIndex:i] isKindOfClass:[Watch class]]){
            Watch *watch=[[Watch alloc]init]; watch=[ContactsArray objectAtIndex:i];
            if ([watch.sim isEqualToString:phoneNum]){return YES;}
        }
        
    }
    for (int i=0;i<SosContactsArray.count;i++)
    {
        if ([[SosContactsArray objectAtIndex:i] isKindOfClass:[Manager class]])
        {
            Manager *manager=[[Manager alloc]init]; manager=[SosContactsArray objectAtIndex:i];
            if ([manager.phone isEqualToString:phoneNum]){return YES;}
        }
        if ([[SosContactsArray objectAtIndex:i] isKindOfClass:[Contact class]]){
            Contact *contact=[[Contact alloc]init]; contact=[SosContactsArray objectAtIndex:i];
            if ([contact.phoneNum isEqualToString:phoneNum]){return YES;}
        };
        if ([[SosContactsArray objectAtIndex:i] isKindOfClass:[Watch class]]){
            Watch *watch=[[Watch alloc]init]; watch=[SosContactsArray objectAtIndex:i];
            if ([watch.sim isEqualToString:phoneNum]){return YES;}
        }
        
    }
    
    
    return NO;
}
- (IBAction)phoneTextFieldChange:(id)sender {
    self.phoneNumberTextField.text=[Tooler validateNumber:self.phoneNumberTextField.text];
}

@end
